from dbus.glib import *
import gobject
import dbus
import array
import time
import location
import sched

#######################################
# gps device
#######################################
class GPS():


    def __init__(self):
        self.control = location.GPSDControl.get_default()
        self.device = location.GPSDevice()
        self.control.set_properties(preferred_method=location.METHOD_USER_SELECTED,
                       preferred_interval=location.INTERVAL_2S)
        self.coords = {}

    def read(self):
        self.coords = {}
        self.on()
        if not self.device:
            return self.coords
        if self.device.fix:
            if self.device.fix[1] & location.GPS_DEVICE_LATLONG_SET:
                self.coords = {'t_query': time.time(),
                        't':   self.device.fix[2],    #time
                        'lat': self.device.fix[4],    #latitude
                        'lng': self.device.fix[5],    #longitude
                        'r':   self.device.fix[6]     #accuracy radius
                        }
        return self.coords

    def on(self):        
        if not self.device.online:
            #self.device.reset_last_known()
            self.control.start()
        #    print "gps start"

    def off(self):
        #if self.device.online:
        self.control.stop()
        #    print "gps stop"


########################################
# celluar id
########################################
class Celluar():
    def __init__(self):
        #threading.Thread.__init__(self)
        bus = dbus.SystemBus()
        dbus_object = bus.get_object('com.nokia.phone.net', 
                                     '/com/nokia/phone/net')
        self.dbus_interface = dbus.Interface(dbus_object, 'Phone.Net')
        self.mark = " > "
        self.cell = {}

    def read(self):
        global point
        now = time.time()

        tuple_sigstrength = self.dbus_interface.get_signal_strength()
        c_sig = tuple_sigstrength[1]

        tuple_cellstatus = self.dbus_interface.get_registration_status()
        (c_status, c_lac, c_id, c_mnc, c_mcc, c_type, c_services, c_err) \
            = tuple_cellstatus

        #print '%f: CID=%d, LAC=%d, MNC=%d, MCC=%d, SIG=-%ddbm' \
        #    %(now, c_id, c_lac, c_mnc, c_mcc, c_sig)

        self.cell = {'t': now,
            'cid': c_id, 
            'lac': c_lac, 
            'mnc': c_mnc, 
            'mcc': c_mcc,
            'dbm': -c_sig,
        }
        return self.cell


######################################
##  accelerometer
######################################
class Accel():


    def __init__(self):
        self.bus = dbus.SystemBus()             
        self.accel = self.bus.get_object('com.nokia.mce',
            '/com/nokia/mce/request',
            'com.nokia.mce.request')
        self.coords = []
        self.s = sched.scheduler(time.time, time.sleep)
    
    def dbus_read(self): 
        orientation , stand , face , x , y , z = self.accel.get_device_orientation()
        #self.coords =  {'t':time.time(),
        #          'orientation':orientation, 
        #          'stand':stand, 
        #          'face':face, 
        #          'x':x,
        #          'y':y, 
        #          'z':z
        #        }
        self.coords = [x , y , z]
        return self.coords

    def readraw(self):
        f = open("/sys/class/i2c-adapter/i2c-3/3-001d/coord", 'r' )
        self.coords.append([int(w) for w in f.readline().split()])
        f.close()


    def read(self,n=1):
        self.coords = []
        for i in range(n):
            self.s.enter(i*0.01, 1, self.readraw, ())
        self.s.run()
        return self.coords
#######################################
# wireless Lan device
#######################################
class Wlan():
    

    def __init__(self):    
        self.aps = {}   
        self.loop = None
        self.bus = dbus.SystemBus()
        self.bus.add_signal_receiver(self.scan_results, 
                                dbus_interface="com.nokia.wlancond.signal", 
                                signal_name="scan_results")
        self.wlancond = self.bus.get_object('com.nokia.wlancond',
                                '/com/nokia/wlancond/request')
        self.request = dbus.Interface(self.wlancond, 'com.nokia.wlancond.request')

    def scan_results(self,*args):
        self.aps = {}
        for i in  range(0, args[0]):
            pos = 1+(i*5)
            (essid, bssid, rssi, channel, capbits) = args[pos:pos+5]
            address = "%02X:%02X:%02X:%02X:%02X:%02X" % \
                        (bssid[0],bssid[1],bssid[2],bssid[3],bssid[4],bssid[5])
            essid = str("%s" % (array.array("b", essid).tostring()))
            essid = essid.replace("\x00","")
            #channel = "%d" % (channel)
            sig = "%d" % (rssi)
            self.aps[address] = [essid,sig]
        self.loop.quit()
        self.aps['t'] = time.time()
        #print "3 -> " + str(time.time())
        #self.loop = None

    def scan(self):
        #print "1 -> " + str(time.time())
        try:
            self.request.scan(dbus.Int32(4), dbus.ByteArray([]), dbus.Int32(2))
        except:
            self.aps = {}
            return {}
        #print "2 -> " + str(time.time())
        self.loop=gobject.MainLoop()
        self.loop.run()
        #print "4 -> " + str(time.time())
        return self.aps

#####################################
# read wifi (method 2)
#####################################
"""
from pythonwifi.iwlibs import Wireless
class Wifi():
    
    
    def __init__(self):
        pass

    def scan(self):
        iface="wlan0"
        w=Wireless(iface)
        try:
            results = w.scan()
        except IOError, ex:
            results = {}

        dt = {}
        for i in results:
            d = [i.essid,i.quality.getSignallevel()]
            #d={
	        #'bssid':    i.bssid,
	        #'essid':    i.essid,
	        #'mode':	    i.mode,
            #'signal':	i.quality.getSignallevel(),
	        #'quality':  {
	        #    'quality':	i.quality.quality,
	        #    'noise':	i.quality.getNoiselevel(),
	        #    'signal':	i.quality.getSignallevel(),
	        #    },
	        #'freq':	    {
	        #    'm':    i.frequency.m * \
		    #        (10 ** i.frequency.e) / (10 ** 6), # Frequency in MHz
	        #    'e':    i.frequency.e,
	        #    },
	        #'rates':    i.rate,
	        #}
            dt[i.bssid]=d
        dt['t'] = time.time()
        return dt
"""

if __name__ ==  "__main__":
    """
    w = Wlan()
    def wifiscan():
        w.scan()

    c = Celluar()
    def cellread():
        c.read()

    g = GPS()
    def gpsread():
        g.read()

    a = Accel()
    def accread():
        a.read(50)

    sc = sched.scheduler(time.time, time.sleep)
    for i in range(50):
        sc.enter(i*2, 1, accread, ())
        sc.run()
    """
    """
    time.sleep(5)
    g = GPS()
    time.sleep(5)
    g.on()
    time.sleep(5)
    for i in range(50):
        t = time.time()
        g.read()    
        t1 = time.time()
        time.sleep(2-(t1-t))
    g.off()
    time.sleep(100)
    
    """

    """
    w = Wlan()
    for i in range(50):
        t = time.time()
        w.scan()
        time.sleep(1)
        t1 = time.time()
        if (2-(t1-t))>0:
            time.sleep(2-(t1-t))
    time.sleep(100)
    """

    """
    c = Celluar()
    for i in range(50):
        t = time.time()
        c.read()
        time.sleep(1)
        t1 = time.time()
        time.sleep(2-(t1-t))
    time.sleep(100)
    """

    
    a = Accel()
    print time.time()
    print a.read(50)
    print time.time()
    """    
    for i in range(1):
        #a.dbus_read()
        #t = time.time()
        for j in range(200):
            print time.time()
            print a.read()
            #time.sleep(0.005)
        #t1 = time.time()
        time.sleep(2-(t1-t))        
    time.sleep(100)
    """

